local STool = {}

CatmullRomCams.SToolMethods.Layout  = STool
CatmullRomCams.SToolMethods.ToolObj = nil

function STool.LeftClick(self, trace)
	
	local thisPlayer = self:GetOwner()
	trace = {}
	trace.start  = thisPlayer:GetShootPos()
	trace.endpos = trace.start + (thisPlayer:GetAimVector() * 99999999)
	trace.filter = thisPlayer
	trace = util.TraceLine(trace)
	
	local key = self:GetClientNumber("key")
	
	if key == -1 then return false end

	if CLIENT then   
	return true
	end
	
	local plyID = thisPlayer:UniqueID()
		
	local bank_delta_max  =  self:GetClientNumber("bankdelta_max")
	local bank_multiplyer =  self:GetClientNumber("bank_multi")
	
	local zoom = self:GetClientNumber("camera_zoom")
	
	local roll         =  self:GetClientNumber("roll")
	
	if trace.Entity then
		if trace.Entity:IsPlayer() then return end
		
		if (trace.Entity:GetClass() == "sent_catmullrom_camera") and (thisPlayer:GetShootPos():Distance(trace.HitPos) < 512) then
					
			trace.Entity:SetZoom(zoom or 75)
			
			trace.Entity:ToggleHighlighted()

			return true
		end
	end
	
	CatmullRomCams.Tracks[plyID]      = CatmullRomCams.Tracks[plyID]      or {}
	CatmullRomCams.Tracks[plyID][key] = CatmullRomCams.Tracks[plyID][key] or {}
	
	local track_index = #CatmullRomCams.Tracks[plyID][key] + 1	

	local camera = ents.Create("sent_catmullrom_camera")
	
	if not (camera and camera.IsValid and camera:IsValid()) then return end
	
	local ang = thisPlayer:EyeAngles()
	
	camera:SetAngles(ang)
	camera:SetPos(trace.StartPos)
	camera:Spawn()
	
	camera:SetPlayer(thisPlayer)


	if CatmullRomCams.Tracks[plyID][key][track_index - 1] and CatmullRomCams.Tracks[plyID][key][track_index - 1]:IsValid() then
		CatmullRomCams.Tracks[plyID][key][track_index - 1]:DeleteOnRemove(camera)
		CatmullRomCams.Tracks[plyID][key][track_index - 1]:SetNWEntity("ChildCamera", camera)
		
//		CatmullRomCams.Tracks[plyID][key][track_index - 1]:SetNWInt("TEST", math.random(0,100))

	else
		camera:SetNWBool("IsMasterController", true)
		camera:SetNWEntity("ControllingPlayer", thisPlayer)
	
		camera:SetKey(key)
		
		numpad.OnDown(thisPlayer, key, "CatmullRomCamera_Toggle", camera)
	end
	
	CatmullRomCams.Tracks[plyID][key][track_index] = camera
	

	camera:SetZoom(zoom or 75)
	
	camera:SetNWEntity("MasterController", CatmullRomCams.Tracks[plyID][key][1])
	
	camera.UndoData = {}
	camera.UndoData.PID = plyID
	camera.UndoData.Key = key
	camera.UndoData.TrackIndex = track_index
	
	undo.Create("CatmullRomCamera")
		undo.AddEntity(camera)
		
		if track_index ~= 1 then
			undo.AddEntity(constraint.NoCollide(camera, CatmullRomCams.Tracks[plyID][key][1], 0, 0))
		end
		
		undo.SetPlayer(thisPlayer)
	undo.Finish()
	
	thisPlayer:AddCleanup("catmullrom_cameras", camera)
	
	return true, camera
end

function STool.RightClick(self, trace)
	-- Fun Fact: If you check the _G table on the server for the key 'camera' you can find the last camera
	--           requested by the camera STool's Rightclick method because Garry, in his omniscience, declared
	--           that it would be best if he didn't add a local in front of the variable declaration. :loleyes:
	
	if CLIENT then return true end
	
	local ply = self:GetOwner()
	
	if ply:KeyDown(IN_SPEED) and self:ValidTrace(trace) then
		
		ply:ConCommand("catmullrom_camera_zoom "        .. (trace.Entity.Zoom or 75) .. "\n")
				
		return true
	end
	
	local _, camera = self:LeftClick(trace)
	if not (camera and camera.IsValid and camera:IsValid()) then return end

	if trace.Entity:IsWorld() then
		camera:SetTracking(ply, trace.Entity:WorldToLocal(trace.HitPos))
	else
		camera:SetTracking(trace.Entity, trace.Entity:WorldToLocal(trace.HitPos))
	end
	
	return true
end

function STool.Reload(self, trace)
	if not self:ValidTrace(trace) then return end
	if CLIENT then return true end
	
	local ply = self:GetOwner()
	
	if ply:KeyDown(IN_SPEED) then
		
		ply:ConCommand("catmullrom_camera_zoom 75\n")
		
	else
		
		
		trace.Entity:SetZoom(75)
	end
	
	return true
end

function STool.Think(self)
	
	if CLIENT then
		localPlayer=LocalPlayer()

		trace = {}
		trace.start  = localPlayer:GetShootPos()
		trace.endpos = trace.start + (localPlayer:GetAimVector() * 99999999)
		trace.filter = localPlayer
		trace = util.TraceLine(trace)

		if trace.Entity then
			if trace.Entity:IsPlayer() then 
				return 
			end
			
			//if (trace.Entity:GetClass() == "sent_catmullrom_camera") then
			//	print("ID " .. trace.Entity.CLTrackIndex)
			//end

			if (trace.Entity:GetClass() == "sent_catmullrom_camera") and 
				(localPlayer:GetShootPos():Distance(trace.HitPos) < 512) then
				trace.Entity:SetNWInt("MouseOverIdx", trace.Entity.CLTrackIndex)
			end
		end
	end

if SERVER then return end
	
	CatmullRomCams.SToolMethods.ToolObj = self -- Hackz
end

function STool.BuildCPanel(panel)
	--panel:AddControl("Header", {Text = "Catmull-Rom Cinematic Cameras: Track Layout Creator", Description = "Use this to create your track's layout!"})
	
	panel:AddControl("Numpad",   {Label = "Track Trigger Key: ", Command = "catmullrom_camera_key", ButtonSize = 22})
	
	panel:AddControl("Slider",   {Label = "Bank Delta: ",         Description = "(Change Speed Max) How fast is the maximum we should be able to bank in one frame? (1 = As much as we want.)", Type = "Float", Min = "0.01", Max = "1", Command = "catmullrom_camera_bankdelta_max"})
	panel:AddControl("Slider",   {Label = "Bank Multiplier: ",    Description = "(Magnify Banking Effect) How much should we multiply the amount we bank in one frame? (1 = No change.)",       Type = "Float", Min = "0.01", Max = "5", Command = "catmullrom_camera_bank_multi"})
	
	panel:AddControl("Slider",   {Label = "Zoom: ", Description = "Default is 75. Press 'USE' (typically 'e' on your keyboard) to reset Zoom & Roll.", Type = "Float", Min = ".1", Max = "170",   Command = "catmullrom_camera_zoom"})
	
	panel:AddControl("Slider",   {Label = "Roll: ",        Description = "DO A BARREL ROLL! Beware! Make sure you add a node with '0' if you just want to make part of the track rolling;\nOtherwise the camera will jump!", Type = "Float", Min = "-180", Max = "180", Command = "catmullrom_camera_roll"})
	
	--panel:AddControl("CheckBox", {Label = "Don't Stop At Track End: ", Description = "(Requires to be on Control node.) Just stay at the last position at the end of the track.", Command = "catmullrom_camera_enable_stay_on_end"})
	--panel:AddControl("CheckBox", {Label = "Loop Track: ",              Description = "(Requires to be on Control node & that the option above is on.) But loop instead.", Command = "catmullrom_camera_enable_looping"})
end
